<template>
  <div class="authenticate">

    <div class="tit">
      <div style="position: absolute;right: .2rem;">
        <el-button @click="goback" size="small">取消鉴定</el-button>
      </div>
    </div>

    <!--主要容器-->
    <div class="aut_main">
      <div class="aut_main_l" style="flex: 5;overflow: hidden">
        <!--大图-->
        <div class="big_image" style="height: calc(100% - .2rem);background-color: #f4f6f8;">
          <!--set-->
          <div class="big_image_set" style="padding-right: 0;">
            <div class="alpt" title="查看大图">
              <viewer :images="signImages" style="opacity: 0">
                <img v-for="src in signImages" :src="src" :key="src" width="50">
              </viewer>
              <!--<img src="../../static/images/alpt.png" alt="">-->
            </div>
            <div @click="rp" title="查看对比图">
              <img src="../../static/images/对比.png" alt="">
            </div>
            <div @click="openTip" v-if="abilityList.indexOf('edit') != -1" title="自动识别">
              <img src="../../static/images/扫一扫.png" alt="">
            </div>
            <div @click="del" v-if="abilityList.indexOf('edit') != -1" title="删除">
              <img src="../../static/images/del.png" alt="">
            </div>
          </div>
          <!--set-->
          <!--图片-->
          <img class="big_image_img" v-show="isMp4(bigimage) == '照片'" id="pcr" :src="bigimage" alt="">
          <video style="width: 100%;height: 100%;" v-show="isMp4(bigimage) == '视频'" :src="bigimage" autoplay
            controls></video>
          <!--图片-->
          <!--文字-->
          <div class="big_image_txt" style="top: .1rem;margin-left: 0;">
            <!--<span>拍摄时间：{{messageObj.shootingTime}}</span>-->
            &nbsp; &nbsp; &nbsp;
            <span>经度：{{ messageObj.lon }}</span>
            &nbsp; &nbsp; &nbsp;
            <span>纬度：{{ messageObj.lat }}</span>
          </div>
          <!--文字-->

        </div>
        <!--大图-->
      </div>
      <div class="aut_main_r" style="flex: 5">
        <!--表单-->
        <div class="aut_main_r_form">
          <div style="background-color: #f4f6f8;padding-top: .2rem;overflow: hidden">
            <el-form style="width: 90%;" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
              class="demo-ruleForm">
              <el-form-item label="拍摄时间" required>
                <!--prop="date"-->
                <el-form-item>
                  <el-date-picker type="datetime" placeholder="选择拍摄时间" v-model="ruleForm.shootingTime"
                    :default-value="c_time(ruleForm.shootingTime)" @change="gettime"
                    style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-form-item>

              <el-form-item label="物种类别" prop="objType">
                <el-radio-group v-model="ruleForm.objType">
                  <el-radio label="兽类"></el-radio>
                  <el-radio label="鸟类"></el-radio>
                  <el-radio label="两栖"></el-radio>
                  <el-radio label="其他"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="物种名称">
                <el-col :span="14">
                  <el-autocomplete style="width: 100%;" class="inline-input" :fetch-suggestions="querySearch"
                    @focus="recently" @input="sec" placeholder="请输入物种名称"
                    v-model="ruleForm.speciesName"></el-autocomplete>
                </el-col>
                <!--<el-col class="line" :span="1">&nbsp;</el-col>-->
                <el-col :span="10">
                  <el-form-item label="无法鉴定">
                    <el-switch @change="unableIdentifyFun" v-model="delivery"></el-switch>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item label="鉴定人" prop="identifyPeople">
                <el-input v-model="ruleForm.identifyPeople"></el-input>
              </el-form-item>
              <el-form-item label="照片编号" prop="imageName">
                <el-input v-model="ruleForm.imageName"></el-input>
              </el-form-item>
              <el-form-item label="照片质量" prop="imageQuality">
                <el-select style="width: 100%;" v-model="ruleForm.imageQuality" placeholder="请选择照片质量">
                  <el-option label="低" value="低"></el-option>
                  <el-option label="中" value="中"></el-option>
                  <el-option label="高" value="高"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="物种数量" prop="animalNum">
                <el-input v-model.number="ruleForm.animalNum"></el-input>
              </el-form-item>
              <el-form-item label="物种性别" prop="speciesGender">
                <el-radio-group v-model="ruleForm.speciesGender">
                  <el-radio label="雄"></el-radio>
                  <el-radio label="雌"></el-radio>
                  <el-radio label="雄雌都有"></el-radio>
                  <el-radio label="难以辨别"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="温度(℃)" prop="temperature">
                <el-input v-model="ruleForm.temperature"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="ruleForm.remark"></el-input>
              </el-form-item>
            </el-form>
            <div style="display: flex;align-items:center;margin-left: 55px;margin-bottom: .1rem;"
              v-if="abilityList.indexOf('edit') != -1">
              <div class="custombtn">
                <span @click="submitForm('ruleForm', 1)">确认鉴定</span>
              </div>
            </div>
          </div>
        </div>
        <!--表单-->
        <!--按钮-->

        <!--按钮-->
      </div>
    </div>
    <!--主要容器-->

    <!--自动识别组件-->
    <automatic ref="autoPhoto" :speciesData="animalData" v-on:nameCallBack="nameCall"></automatic>
    <!--自动识别组件-->

    <div class="areachart" v-if="isac">
      <div class="close" @click="acclose">
        <img src="../../static/images/icon/close.png" alt="">
      </div>

      <div class="acimg">
        <div class="original">
          <img style="width: 7.6rem;height: 5.7rem;" :src="accimg" alt="">
          <div style="position: absolute;top: 0;left: 0;">
            <img style="width: .6rem;height: .6rem;" src="../../static/images/yuantu.png" alt="">
          </div>
        </div>
        <div style="width: 1.6rem;height: 5.7rem;display: flex;align-items: center;justify-content: center">
          <div
            style="width: .8rem;height: .3rem;border-radius: .02rem;background-color: #000000 ;color: #FFFFFF;text-align: center;line-height: .3rem">
            <span>图片对比</span>
          </div>
        </div>
        <div class="similarity">
          <img style="width: 7.6rem;height: 5.7rem;" :src="acbimg" alt="">
          <div style="position: absolute;top: 0;left: 0;">
            <img style="width: .6rem;height: .6rem;" src="../../static/images/duibi.png" alt="">
          </div>
        </div>
      </div>
    </div>


  </div>
</template>
<script>
import api from '../utils/api';
import http from '../utils/http'
import '../../static/jquery-ui-1.12.1/jquery-ui.css'
import '../../static/jquery-ui-1.12.1/jquery-ui'

export default {
  data() {
    return {
      single: false,
      animalData: {
        url: '',
        type: 'animal'
      },
      signImages: [''],
      indexes: 0,
      rm: 0,
      imageList: [],
      bigimage: "",
      messageObj: {},
      change_time: "",
      delivery: false,
      ruleForm: {
        id: "",
        shootingTime: '',//拍摄时间
        objType: '兽类',
        speciesName: '',//物种名称
        identifyPeople: "",//鉴定人
        imageName: "",//照片编号
        imageQuality: "",//照片质量
        animalNum: 1,//物种数量
        speciesGender: "",//物种性别
        temperature: '',//温度
        remark: ''
      },
      rules: {
        date: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        speciesName: [
          { required: true, message: '请输入物种名称', trigger: 'blur' }
        ],
        identifyPeople: [
          { required: true, message: '请输入鉴定人姓名', trigger: 'blur' }
        ],
        imageName: [
          { required: true, message: '请输入照片编号', trigger: 'blur' }
        ],
        imageQuality: [
          { required: true, message: '请选择照片质量', trigger: 'blur' }
        ],
        animalNum: [
          { required: true, message: '数量不能不能为空', trigger: 'blur' }
        ],
        objType: [
          { required: true, message: '请选择物种类别', trigger: 'blur' }
        ],
        speciesGender: [
          { required: true, message: '请选择物种性别', trigger: 'blur' }
        ],
      },
      areaId: "",
      //模糊搜索
      restaurants: [],
      obj: null,
      aclist: [],
      accimg: "",
      acbimg: "",
      acindex: 0,
      isac: false,
      imgimg: {},
      allnum: 0,
      nowpage: 1,
      idlist: [
        {
          groupNum: ""
        }
      ],
      groupId: "",
      tnumber: 1,
      cardxiaolei: "",
      groupNumber: "",
      userName: "",
      abilityList: []
    }
  },
  created() {
    this.areaId = sessionStorage.getItem('areaId');
    this.userName = sessionStorage.getItem('urseName');
    if (localStorage.getItem('arr') == undefined) {
      let arr = [{ value: "无识别结果" }];
      localStorage.setItem('arr', JSON.stringify(arr));
    }
    this.abilityList = sessionStorage.getItem('abilityList');
  },
  mounted() {
    this.getallImageIdentify();
  },
  methods: {
    isMp4(m) {
      let iv = m.split('.');
      if (iv[iv.length - 1].toLowerCase() == 'mp4') {
        return '视频'
      } else {
        return '照片'
      }
    },
    //无法鉴别
    unableIdentifyFun() {
      if (this.delivery) {
        this.ruleForm.speciesName = "无法鉴定"
      } else {
        this.ruleForm.speciesName = ""
      }
    },
    //模糊搜索
    querySearch(queryString, cb) {
      let restaurants = this.restaurants;
      if (restaurants.length > 0) {
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      }
    },
    //模糊搜索2
    createFilter() {
      return (restaurant) => {
        return (restaurant.value.toLowerCase());
      };
    },
    //模糊搜索3
    loadAll() {
      return this.obj;
    },
    recently() {
      this.obj = JSON.parse(localStorage.getItem('arr'));
      this.restaurants = this.loadAll();
    },
    //模糊搜索4
    sec() {
      let vm = this;
      (async function () {
        let res = await http.get(api.queryByInput, {
          areaId: vm.areaId,
          type: vm.ruleForm.objType,
          input: vm.ruleForm.speciesName
        })
        let arr = [];
        if (res.data.length == 0) {
          vm.obj = [{ value: "暂无数据，建议更换关键字" }];
          vm.restaurants = vm.loadAll();
        } else {
          res.data.forEach((e => {
            let z = {
              value: e
            }
            arr.push(z);
          }))
          vm.obj = arr;
          vm.restaurants = vm.loadAll();
        }
      })()
    },
    //提交
    submitForm(formName, flag) {
      let vm = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.shootingTime == '') {
            alert('拍摄时间不能为空');
            return false
          }

          (async function () {
            let res = await http.get(api.queryByInput, {
              areaId: vm.areaId,
              type: vm.ruleForm.objType,
              input: vm.ruleForm.speciesName
            })
            if (res.data.length == 0 && vm.ruleForm.speciesName != '无法鉴定') {
              vm.warn('物种名不存在，请重新填写物种名称');
              vm.ruleForm.speciesName = "";
              return false;
            } else {
              let obj = Object.assign({}, vm.ruleForm);
              obj['ids'] = JSON.parse(sessionStorage.getItem('empty')).id;
              obj.shootingTime = vm.change_time;
              (async function () {
                let res = await http.post(api.infrared.newimageSave, obj)
                if (res.data.message == 'error') {
                  vm.warn(res.data.error)
                } else {
                  vm.success('鉴定完成');
                  vm.goback();
                }
              })()
            }
          })();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //自动识别
    openTip() {
      this.$refs.autoPhoto.showtip();
      this.$refs.autoPhoto.openTip();
      this.$refs.autoPhoto.jcropDestroy();
    },
    nameCall(msg) {
      this.ruleForm.speciesName = msg;
    },
    acclose() {
      this.isac = false;
      this.acindex = 0;
    },
    rp() {
      let vm = this;
      (async function f() {
        let res = await http.get(api.compareImage, {
          input: vm.ruleForm.speciesName
        })
        if (res.data.code == '200') {
          vm.acbimg = res.data.data
        } else {
          vm.acbimg = "../../static/images/np.jpg";
        }
      })()
      this.isac = true;
      this.accimg = this.bigimage;
    },
    AutoSize(Img, maxWidth, maxHeight) {
      let image = new Image();
      image.src = Img;
      image.onload = function () {
        if (image.width < maxWidth && image.height < maxHeight) {
          $("#pcr").css({ width: image.width, height: image.height })
        } else {
          if (maxWidth / maxHeight <= image.width / image.height) {
            $("#pcr").animate({ width: maxWidth, height: maxWidth * (image.height / image.width) }, 'fast');
          } else {
            $("#pcr").animate({ width: maxHeight * (image.width / image.height), height: maxHeight }, 'fast');
          }
        }
      }
    },
    getallImageIdentify() {
      let obj = JSON.parse(sessionStorage.getItem('empty'));
      this.getobj(obj);
      let arr = [];
      if (obj.discernName != null) {
        obj.discernName.split('#').forEach(e => {
          let z = {
            value: e
          }
          arr.push(z)
        })
        localStorage.setItem('arr', JSON.stringify(arr));
      }
      if (obj.discernPath != null) {
        this.bigimage = obj.discernPath;
      } else {
        this.bigimage = obj.accessorySrc;
      }
      this.animalData.url = obj.accessorySrc;
      this.messageObj = Object.assign({}, obj);
      let look_b_i = [];
      let ims = obj.accessorySrc
      look_b_i.push(ims);
      this.signImages = look_b_i;
      let vm = this;
      $(function () {
        let maxWidth = $('.big_image').width();
        let maxHeight = $('.big_image').height();
        let path = $('#pcr').attr('src');
        vm.AutoSize(path, maxWidth, maxHeight);
      })

    },
    //获取对象值
    getobj(o) {
      for (let k in o) {
        if (k == 'objType' && o[k] == null) {
          o[k] = '兽类'
        }
        if (k == 'aloneAuthenticate' && o[k] == null) {
          o[k] = 0;
          this.single = false
        }

        if (k == 'identifyPeople' && o[k] == null) {
          o[k] = this.userName;
        }
        if (k == 'aloneAuthenticate' && o[k] != null) {
          if (o[k] = 1) {
            this.single = true
          } else if (o[k] = 0) {
            this.single = false
          }
        }
      }
      this.change_time = o.shootingTime;
      this.ruleForm = o;
      if (this.ruleForm.discernName != null) {
        this.ruleForm.speciesName = this.ruleForm.discernName.split('#')[0];
      }
    },

    del() {
      let id = JSON.parse(sessionStorage.getItem('empty')).id;
      let vm = this;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        (async function () {
          let res = await http.post(api.infrared.newimageIdentifyDelete,
            {
              id: id
            }
          )
          if (res.data.message == 'error') {
            vm.warn(res.data.error)
          } else {
            vm.$message({
              type: 'success',
              message: '删除成功!'
            });
            vm.goback();
          }
        })()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    goback() {
      this.$router.push({
        path: '/Photo/Emptyphoto',
      });
    },
    //图片处理
    iscloud(p) {
      if (p.split(":")[0] == 'http') {
        return p + '@oosImage|100h'
      }
      if (p.split(":")[0] == 'https') {
        return p + '?x-amz-process=image/resize,h_100,m_lfit'
      }
      return '/iapi' + p
    },
    //时间处理
    c_time(e) {
      let a = (new Date(e))
      return a;
    },
    //获取时间
    gettime(datetime) {
      if (datetime != null) {
        let year = datetime.getFullYear();
        let month = datetime.getMonth() + 1;
        let date = datetime.getDate();
        let Hours = datetime.getHours();
        let Minutes = datetime.getMinutes();
        let Seconds = datetime.getSeconds();

        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (date >= 0 && date <= 9) {
          date = "0" + date;
        }
        if (Hours >= 1 && Hours <= 9) {
          Hours = "0" + Hours;
        }
        if (Minutes >= 0 && Minutes <= 9) {
          Minutes = "0" + Minutes;
        }
        if (Seconds >= 1 && Seconds <= 9) {
          Seconds = "0" + Seconds;
        }
        let t1 = year + "/" + month + "/" + date + " " + Hours + ":" + Minutes + ":" + Seconds;
        this.change_time = t1;
      } else {
        this.change_time = ''
      }

    },
    warn(txt) {
      this.$message({
        message: txt,
        type: 'warning'
      });
    },
    success(txt) {
      this.$message({
        message: txt,
        type: 'success'
      });
    },
  }
}
</script>
<style scoped>
@import "../../static/css/authenticate.css";
</style>
